<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--系部数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="deptName"
              placeholder="请输入系部名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="职称" prop="title">
            <el-select
                v-model="queryParams.title"
                placeholder="请选择职称"
                clearable
                style="width: 240px"
            >
              <el-option
                  v-for="dict in sys_user_title"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Setting"
                @click="openSettings"
            >展示</el-button>
            <el-button
                type="primary"
                plain
                icon="Setting"
                @click="openSettingsDialog"
            >设置</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="50" align="center" />-->
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="职位" align="center" key="posts" prop="posts" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="邮箱" align="center" key="email" prop="email" v-if="columns[0].visible" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[1].visible" :show-overflow-tooltip="true" />

        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 展示设置 -->
    <el-dialog
        title="学院通讯录设置"
        v-model="form.dialogVisible"
        width="30%"
    >
      <p>学院通讯录仅展示将已加入学院用户的姓名/职位/电话/邮箱信息，方便学院老师分享成果与查找联系方式</p>
      <el-row :gutter="20" justify="center">
        <el-col :span="24" style="text-align: center;">
          <el-radio-group v-model="form.showContactList">
            <el-radio label="show">展示</el-radio>
            <el-radio label="hide">不展示(不推荐)</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="24" style="text-align: center;">
          <span class="dialog-footer">
            <el-button @click="form.dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveSettings">保存</el-button>
          </span>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import { changeUserStatus, listUser } from "@/api/system/user";
import { isVisible,updateAllIsDisplayed,resetFromSysUser } from "@/api/team/collegeContact";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex, sys_user_title, sys_user_degree } = proxy.useDict("sys_normal_disable", "sys_user_sex","sys_user_title","sys_user_degree");

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);

// 列显隐信息
const columns = ref([
  { key: 0, label: `邮箱`, visible: true },
  { key: 1, label: `手机号`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `职位`, visible: true },
]);
const data = reactive({
  form: {
    dialogVisible: false,
    showContactList: 'show', // 默认展示
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    title: undefined,
    minAge: undefined,
    maxAge: undefined,
    status: undefined,
    deptId: undefined
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选系部树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 打开设置对话框 */
async function openSettingsDialog() {
  try {
    const response = await isVisible();
    if (response.data) {
      form.value.showContactList = 'show';
    } else {
      form.value.showContactList = 'hide';
    }
    form.value.dialogVisible = true;
  } catch (error) {
    console.error('获取展示状态失败:', error);
    form.value.dialogVisible = true; // 仍然显示对话框，即使获取状态失败
  }
}
async function openSettings() {
  try {
    await resetFromSysUser();
    proxy.$modal.msgSuccess("重置成功");
    const response = await isVisible();
    console.log('获取展示状态:', response.data);
    if (response.data) {
      form.value.showContactList = 'show';
    } else {
      form.value.showContactList = 'hide';
    }
  } catch (error) {
    console.error('重置或获取展示状态失败:', error);
    proxy.$modal.msgError("重置失败");
  }
}

async function saveSettings() {
  try {
    const isDisplayed = form.value.showContactList === 'show' ? 0 : 1;
    await updateAllIsDisplayed(isDisplayed); // 确保 isDisplayed 是整数
    console.log('保存的设置:', form.value.showContactList);
    form.value.dialogVisible = false;
    // 这里可以添加其他保存逻辑
  } catch (error) {
    console.error('保存设置失败:', error);
    proxy.$modal.msgError("保存设置失败");
  }
}

/** 查询系部下拉树结构 */
function getDeptTree() {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
  // deptTreeSelect().then(response => {
  //   deptOptions.value = response.data;
  // });
};
/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });
};
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  // queryParams.value.minAge = undefined;
  // queryParams.value.maxAge = undefined;
  proxy.$refs.tree.setCurrentKey(null);
  handleQuery();
};

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
};
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
};
/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
};

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};


/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    posts: undefined,
    postIds: [],
    roleIds: [],
    age: undefined,
    title: undefined,
    highestDegree: undefined,
    department: undefined,
    joinCollegeDate: undefined
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};


getDeptTree();
getList();
</script>
